<template>
  <view class="container">
    <form @submit="handleSubmit">
      <!-- 表单内容 -->
      <view class="form-group">
        <view class="form-item">
          <text class="label">收货人</text>
          <input 
            class="input" 
            type="text" 
            v-model="formData.userName" 
            placeholder="请输入收货人姓名"
          />
        </view>
        
        <view class="form-item">
          <text class="label">手机号码</text>
          <input 
            class="input" 
            type="number" 
            v-model="formData.phone" 
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </view>

        <view class="form-item">
          <text class="label">所在地区</text>
          <picker 
            mode="region" 
            @change="handleRegionChange" 
            :value="selectedRegion"
          >
            <view class="picker-value">
              <text v-if="selectedRegion[0]">
                {{ selectedRegion.join(' ') }}
              </text>
              <text v-else class="placeholder">请选择所在地区</text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">详细地址</text>
          <textarea 
            class="textarea" 
            v-model="detailAddress" 
            placeholder="请输入详细地址信息（如街道、门牌号等）"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="footer">
        <button class="submit-btn" form-type="submit">保存</button>
      </view>
    </form>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { 
  addAddressUsingPost,
  updateAddressUsingPost,
  getAddressVoByIdUsingGet 
} from '../../backend/addressController';
import { tokenStore } from '../../store/tokenStore';
import type { API } from '../../backend/typings';

const store = tokenStore();

// 表单数据
const formData = ref<API.AddressAddRequest & API.AddressUpdateRequest>({
  addressName: '',
  phone: '',
  userName: '',
});

// 地址选择相关
const selectedRegion = ref<string[]>(['', '', '']);
const detailAddress = ref('');

// 监听地址变化，组合完整地址
watch([selectedRegion, detailAddress], ([region, detail]) => {
  if (region[0] && detail) {
    formData.value.addressName = `${region.join('')}${detail}`;
  } else if (region[0]) {
    formData.value.addressName = region.join('');
  } else if (detail) {
    formData.value.addressName = detail;
  } else {
    formData.value.addressName = '';
  }
});

// 处理地区选择
const handleRegionChange = (e: any) => {
  selectedRegion.value = e.detail.value;
};

// 从完整地址中提取省市区和详细地址
const parseAddress = (fullAddress: string = '') => {
  // 常见的省市区后缀
  const suffixes = ['省', '市', '区', '县', '自治区', '自治州', '特别行政区'];
  let remaining = fullAddress;
  let province = '';
  let city = '';
  let district = '';
  
  // 尝试提取省
  for (const suffix of suffixes) {
    const index = remaining.indexOf(suffix);
    if (index !== -1) {
      province = remaining.slice(0, index + suffix.length);
      remaining = remaining.slice(index + suffix.length);
      break;
    }
  }

  // 尝试提取市
  for (const suffix of suffixes) {
    const index = remaining.indexOf(suffix);
    if (index !== -1) {
      city = remaining.slice(0, index + suffix.length);
      remaining = remaining.slice(index + suffix.length);
      break;
    }
  }

  // 尝试提取区/县
  for (const suffix of suffixes) {
    const index = remaining.indexOf(suffix);
    if (index !== -1) {
      district = remaining.slice(0, index + suffix.length);
      remaining = remaining.slice(index + suffix.length);
      break;
    }
  }

  // 设置提取的值
  if (province || city || district) {
    selectedRegion.value = [province, city, district];
    detailAddress.value = remaining.trim();
  } else {
    // 如果无法解析，则将整个地址作为详细地址
    detailAddress.value = fullAddress;
  }
};

// 是否是编辑模式
const isEdit = ref(false);
const addressId = ref<number>();

// 获取地址详情
const fetchAddressDetail = async (id: number) => {
  try {
    const token = store.getToken;
    const res = await getAddressVoByIdUsingGet(
      { id },
      token ? {
        header: {
          'Authorization': token
        }
      } : undefined
    );
    if (res?.code === 0 && res?.data) {
      const { addressName, phone, userName } = res.data;
      formData.value = {
        addressName: addressName || '',
        phone: phone || '',
        userName: userName || '',
      };
      // 解析地址
      parseAddress(addressName);
    }
  } catch (error) {
    console.error('获取地址详情失败：', error);
    uni.showToast({
      title: '获取地址详情失败',
      icon: 'none'
    });
  }
};

// 表单验证
const validateForm = () => {
  const { addressName, phone, userName } = formData.value;
  
  if (!userName) {
    uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    });
    return false;
  }
  
  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    });
    return false;
  }
  
  if (!selectedRegion.value[0]) {
    uni.showToast({
      title: '请选择所在地区',
      icon: 'none'
    });
    return false;
  }
  
  if (!detailAddress.value) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    });
    return false;
  }
  
  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return;
  
  try {
    const token = store.getToken;
    const options = token ? {
      header: {
        'Authorization': token
      }
    } : undefined;

    let res;
    if (isEdit.value && addressId.value) {
      res = await updateAddressUsingPost(
        { ...formData.value, id: addressId.value },
        options
      );
    } else {
      res = await addAddressUsingPost(
        formData.value,
        options
      );
    }

    if (res?.code === 0) {
      uni.showToast({
        title: isEdit.value ? '修改成功' : '添加成功',
        icon: 'success'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } catch (error) {
    console.error(isEdit.value ? '修改地址失败：' : '添加地址失败：', error);
    uni.showToast({
      title: isEdit.value ? '修改失败' : '添加失败',
      icon: 'none'
    });
  }
};

// 页面加载
onLoad((options) => {
  if (options?.id) {
    isEdit.value = true;
    addressId.value = Number(options.id);
    fetchAddressDetail(addressId.value);
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.form-group {
  background: #fff;
  padding: 0 30rpx;
  margin-top: 20rpx;
}

.form-item {
  display: flex;
  align-items: center;
  min-height: 100rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
}

.input {
  flex: 1;
  height: 100rpx;
  font-size: 28rpx;
}

.textarea {
  flex: 1;
  height: 160rpx;
  font-size: 28rpx;
  padding: 20rpx 0;
}

.picker-value {
  flex: 1;
  font-size: 28rpx;
  padding: 20rpx 0;
  min-height: 44rpx;
}

.placeholder {
  color: #999;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: #fff;
}

.submit-btn {
  width: 100%;
  height: 80rpx;
  background: #ff5722;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 